package com.example.androidshixi;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;

public class AccountManagementActivity extends AppCompatActivity {

    private ListView accountListView;
    private Button addAccountButton;
    private DatabaseHelper databaseHelper;
    private List<String> accountList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_management);

        accountListView = findViewById(R.id.account_list_view);
        addAccountButton = findViewById(R.id.add_account_button);
        databaseHelper = new DatabaseHelper(this);
        accountList = new ArrayList<>();

        // 获取所有账号
        loadAccounts();

        // 设置适配器
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, accountList);
        accountListView.setAdapter(adapter);

        // 处理添加账号按钮点击事件
        addAccountButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AccountManagementActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });

        // 处理短按事件，跳转到修改密码界面
        accountListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String username = accountList.get(position);
                Intent intent = new Intent(AccountManagementActivity.this, ChangePasswordActivity.class);
                intent.putExtra("username", username);
                startActivity(intent);
            }
        });

        // 处理长按事件，删除账号
        accountListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                String username = accountList.get(position);
                boolean isDeleted = databaseHelper.deleteUser(username);
                if (isDeleted) {
                    Toast.makeText(AccountManagementActivity.this, "账号删除成功", Toast.LENGTH_SHORT).show();
                    accountList.remove(position);
                    adapter.notifyDataSetChanged();
                } else {
                    Toast.makeText(AccountManagementActivity.this, "账号删除失败", Toast.LENGTH_SHORT).show();
                }
                return true;
            }
        });
    }

    private void loadAccounts() {
        accountList = databaseHelper.getAllUsernames();
    }
}